#include "bus/swi2c.h"
#include <stddef.h>
#include <stdint.h>

int i2c_r8v8_read(swi2c_t* i2c, uint8_t device_address, uint8_t* memory_address, uint8_t* buffer, uint32_t length)
{
	int i = 0;
	int response = 0;

	if (memory_address != NULL) {
		/* 起始信号 */
		swi2c_start(i2c);

		/* 发送设备地址, 写 */
		swi2c_send_byte(i2c, device_address << 1);
		response = swi2c_wait_response(i2c);
		if (response != 0) {
			return -1;
		}

		/* 发送寄存器地址 */
		swi2c_send_byte(i2c, *memory_address);
		response = swi2c_wait_response(i2c);
		if (response != 0) {
			return -2;
		}
	}

	/* 起始信号 */
	swi2c_start(i2c);

	/* 发送设备地址, 读 */
	swi2c_send_byte(i2c, (device_address << 1) + 1);
	response = swi2c_wait_response(i2c);
	if (response != 0) {
		return -3;
	}

	/* 读取寄存器数据 */
	if (buffer != NULL && length > 0) {
		for (i = 0; i < (length - 1); i++) {
			buffer[i] = swi2c_receive_byte(i2c);
			swi2c_response(i2c);
		}

		buffer[i] = swi2c_receive_byte(i2c);
		swi2c_no_response(i2c);
	}

	swi2c_stop(i2c);

	return 0;
}

int i2c_r8v8_write(swi2c_t* i2c, uint8_t device_address, uint8_t* memory_address, uint8_t* buffer, uint32_t length)
{
	int i = 0;
	int response = 0;

	/* 起始信号 */
	swi2c_start(i2c);

	/* 发送设备地址 */
	swi2c_send_byte(i2c, device_address << 1);
	response = swi2c_wait_response(i2c);
	if (response != 0) {
		return -1;
	}

	/* 发送寄存器地址 */
	if (memory_address != NULL) {
		swi2c_send_byte(i2c, *memory_address);
		response = swi2c_wait_response(i2c);
		if (response != 0) {
			return -2;
		}
	}

	/* 发送寄存器数据 */
	if (buffer != NULL && length > 0) {
		for (i = 0; i < length; i++) {
			swi2c_send_byte(i2c, buffer[i]);
			response = swi2c_wait_response(i2c);
			if (response != 0) {
				return -3;
			}
		}
	}

	swi2c_stop(i2c);

	return 0;
}